package com.xiaobaibai.security.master_token.provider;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.xiaobaibai.common.UserCommon;
import com.xiaobaibai.myExcetion.SecurityMyException;
import com.xiaobaibai.security.master_token.token.JwtAuthenticationToken;
import com.xiaobaibai.service.ITokenService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;

import java.util.Map;

public class JwtAuthenticationProvider implements AuthenticationProvider {

//    @Autowired
    private ITokenService tokenService;

    public JwtAuthenticationProvider(ITokenService tokenService) {
        this.tokenService = tokenService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //转为自己的token
        JwtAuthenticationToken jwtAuthenticationToken=(JwtAuthenticationToken)authentication;

        String token = (String) jwtAuthenticationToken.getPrincipal();//获取存入的token

        Map<String,Object> map = tokenService.checkToken(token);

        if(map==null)
            throw new SecurityMyException("非法令牌");

        //创建新的token,用另一个构造方法,它会把认证设置为true,  入参为 用户信息+权限
        JwtAuthenticationToken okToken=
                new JwtAuthenticationToken(map.get("userId"),map.get("decodedJWT"),
                        AuthorityUtils.commaSeparatedStringToAuthorityList(
                                UserCommon.userRole));

        okToken.setDetails(jwtAuthenticationToken.getDetails());//不要漏

        return okToken;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        //判断传进来的class是否是我们自当定义的token,对应的token要用对应的provider
        return JwtAuthenticationToken.class.isAssignableFrom(aClass);
    }

}
